<template>
  <div class="fixed inset-0 bg-black/50 z-50 flex items-center justify-center p-2 backdrop-blur-sm" @click.self="close">
    <div class="bg-white rounded-xl shadow-xl w-full max-w-4xl max-h-[90vh] flex flex-col overflow-hidden animate-in">
      <div
          class="flex items-center justify-between p-3 border-b border-gray-100 bg-gradient-to-r from-purple-50 to-indigo-50">
        <h3 class="text-lg font-bold bg-gradient-to-r from-purple-700 to-indigo-700 inline-block text-transparent bg-clip-text">
          创建新帖子</h3>
        <button class="p-1.5 rounded-full hover:bg-gray-100 transition-colors" @click="close">
          <i class="fas fa-times text-gray-500 hover:text-gray-700 transition-colors"></i>
        </button>
      </div>

      <div class="flex-1 overflow-y-auto p-3 bg-gray-50">
        <div class="grid grid-cols-1 gap-3">
          <div class="bg-white rounded-lg shadow-sm p-3 border border-gray-100 hover:shadow-md transition-shadow">
            <label class="block text-xs font-medium text-gray-700 mb-1">标题<span
                class="text-red-500">（可不填）</span></label>
            <input
                type="text"
                v-model="post.title"
                class="w-full px-2.5 py-1.5 border border-gray-200 rounded-lg focus:ring-2  outline-none transition-all text-sm"
                placeholder="请输入一个吸引人的标题"
            >
            <div class="mt-3">
              <label class="block text-xs font-medium text-gray-700 mb-1">内容</label>
              <textarea
                  v-model="post.content"
                  rows="6"
                  class="w-full px-2.5 py-1.5 border border-gray-200 rounded-lg focus:ring-2  outline-none transition-all text-sm resize-none"
                  placeholder="分享你的想法、经验或故事..."
              ></textarea>
            </div>
          </div>


          <div class="grid grid-cols-1 md:grid-cols-3 gap-3">
            <!-- 发布时间 -->
            <div class="bg-white rounded-lg shadow-sm p-3 border border-gray-100 hover:shadow-md transition-shadow">
              <label class="block text-xs font-medium text-gray-700 mb-1">定时发布</label>
              <input
                  type="datetime-local"
                  v-model="post.publishTime"
                  class="w-full px-2.5 py-1.5 border border-gray-200 rounded-lg focus:ring-2 outline-none transition-all text-sm"
              >
            </div>

            <!-- 发布范围 -->
            <div class="bg-white rounded-lg shadow-sm p-3 border border-gray-100 hover:shadow-md transition-shadow">
              <label class="block text-xs font-medium text-gray-700 mb-1">发布范围</label>
              <select
                  v-model="post.visibility"
                  class="w-full px-2.5 py-1.5 border border-gray-200 rounded-lg focus:ring-2 outline-none transition-all text-sm"
              >
                <option v-for="visibility in visibilityList" :key="visibility.value" :value="visibility.value">
                  <div class="flex items-center">
                    <span>{{ visibility.label }}</span>
                  </div>
                </option>
              </select>
            </div>

            <!-- 社区信息 -->
            <div class="bg-white rounded-lg shadow-sm p-3 border border-gray-100 hover:shadow-md transition-shadow"
                 v-if="post.visibility !== 'PUBLIC_POST'">
              <label class="block text-xs font-medium text-gray-700 mb-1">社区</label>
              <div class="relative">
                <div
                    class="w-full px-2.5 py-1.5 border border-gray-200 rounded-lg focus:ring-2 outline-none transition-all text-sm cursor-pointer"
                    @click="showCommunityDropdown = !showCommunityDropdown"
                >
                  <div class="flex items-center">
                    <img :src="selectedCommunity.avatar" alt="Community Avatar" class="w-6 h-6 rounded-full mr-2">
                    <span>{{ selectedCommunity.name }}</span>
                  </div>
                </div>
                <ul
                    v-if="showCommunityDropdown"
                    class="absolute z-10 w-full bg-white border border-gray-200 rounded-lg shadow-md max-h-40 overflow-y-auto"
                >
                  <li
                      v-for="community in myCommunity"
                      :key="community.id"
                      class="px-2.5 py-1.5 hover:bg-gray-100 cursor-pointer flex items-center"
                      @click="selectCommunity(community)"
                  >
                    <img :src="community.avatar" alt="Community Avatar" class="w-6 h-6 rounded-full mr-2">
                    <span>{{ community.name }}</span>
                  </li>
                </ul>
              </div>
            </div>
          </div>

          <!-- 图片资源 -->
          <div class="bg-white rounded-lg shadow-sm p-3 border border-gray-100 hover:shadow-md transition-shadow"
               v-if="post.visibility !== 'COMMUNITY_NOTICE'">
            <label class="block text-xs font-medium text-gray-700 mb-1.5">
              添加媒体 <span class="text-[10px] text-gray-500">(图片和视频最多共12个)</span>
            </label>
            <div class="grid grid-cols-5 gap-1.5">
              <div
                  class="aspect-square border-2 border-dashed border-gray-200 rounded-lg flex items-center justify-center cursor-pointer hover:border-purple-400 transition-colors group"
                  @click="openFileDialog"
                  :class="{ 'opacity-50 cursor-not-allowed': mediaCount >= 12 }"
                  :disabled="mediaCount >= 12"
              >
                <div class="text-center">
                  <i class="fas fa-plus text-gray-400 group-hover:text-purple-500 transition-colors text-[10px]"></i>
                  <p class="text-[20px] text-gray-400 mt-0.5">图片/视频</p>
                </div>
                <input type="file" accept="image/*,video/*" class="hidden" ref="fileInput" @change="handleFileUpload">
              </div>

              <div v-for="(item, index) in allMedia" :key="item.id"
                   class="aspect-square relative overflow-hidden rounded-lg shadow-sm hover:shadow-md transition-shadow group">
                <div class="absolute top-1 left-1 z-10 bg-black/50 text-white text-[10px] px-1 py-0.5 rounded-full">
                  {{ index + 1 }}
                </div>
                <div v-if="item.type === 'image'" class="w-full h-full">
                  <img :src="item.url" :alt="`Uploaded Image ${item.imageId}`" class="w-full h-full object-cover">
                </div>
                <div v-else class="w-full h-full bg-gray-50 flex items-center justify-center">
                  <video :src="item.url" controls class="w-full h-full object-cover" :id="item.videoId"></video>
                </div>
                <div class="absolute top-1 right-1 z-10">
                  <button
                      class="bg-white/90 text-red-500 rounded-full w-5 h-5 flex items-center justify-center hover:bg-white hover:text-red-700 transition-colors shadow-sm"
                      @click.stop="removeMedia(index)"
                  >
                    <i class="fas fa-trash text-[20px]"></i>
                  </button>
                </div>
                <span v-if="item.type === 'video'"
                      class="absolute bottom-1 left-1 bg-purple-500 text-white text-[10px] px-1 py-0.5 rounded-full">视频</span>
              </div>
            </div>
            <div v-if="mediaCount >= 12" class="mt-1.5 text-[10px] text-red-500">
              <i class="fas fa-exclamation-circle mr-0.5"></i>已达到媒体数量上限(12个)
            </div>
          </div>

          <div class="bg-white rounded-lg shadow-sm p-3 border border-gray-100 hover:shadow-md transition-shadow"
               v-if="post.visibility !== 'COMMUNITY_NOTICE'">
            <label class="block text-xs font-medium text-gray-700 mb-1.5">添加话题</label>
            <div class="flex flex-wrap gap-1.5 mb-1.5">
              <span v-for="(tag, index) in post.tags" :key="index"
                    class="bg-purple-50 text-purple-700 px-1.5 py-0.5 rounded-full text-[10px] flex items-center">
                #{{ tag }}
                <button @click.stop="removeTag(index)"
                        class="ml-1 text-purple-500 hover:text-purple-700 transition-colors">
                  <i class="fas fa-times-circle text-[10px]"></i>
                </button>
              </span>
            </div>

            <div class="flex" v-if="post.visibility !== 'COMMUNITY_NOTICE'">
              <input
                  type="text"
                  v-model="newTag"
                  @keyup.enter="addTag"
                  class="w-2/6 px-2.5 py-1.5 border border-gray-200 rounded-l-lg focus:ring-2 outline-none transition-all text-sm"
                  placeholder="添加话题，按Enter键确认"
              >
              <button
                  class="px-2.5 py-1.5 bg-purple-500 text-white rounded-r-lg hover:bg-purple-600 transition-colors text-sm"
                  @click="addTag"
              >
                <i class="fas fa-plus mr-0.5 text-[10px]"></i>添加
              </button>
            </div>
          </div>

        </div>
      </div>

      <div class="p-3 border-t border-gray-100 flex justify-end space-x-2 bg-white">
        <button
            class="px-3 py-1.5 border border-gray-200 rounded-lg hover:bg-gray-50 transition-colors text-sm font-medium"
            @click="close"
        >
          取消
        </button>
        <button
            class="px-3 py-1.5 bg-gradient-to-r from-purple-500 to-indigo-600 text-white rounded-lg hover:from-purple-600 hover:to-indigo-700 transition-all shadow-sm hover:shadow-md text-sm font-medium"
            @click="submitPost"
            :disabled="isSubmitting"
        >
          <i class="fas fa-paper-plane mr-0.5"></i>
          <span v-if="!isSubmitting">发布</span>
          <span v-else>
            <i class="fas fa-spinner fa-spin mr-0.5"></i>发布中...
          </span>
        </button>
      </div>
    </div>

    <!-- 在模板中添加进度显示 -->
    <div v-for="(file, index) in uploadQueue" :key="index">
      {{ file.name }} - {{ uploadProgress[index] }}%
    </div>

  </div>
</template>

<script>
import {addPost} from "@/api/post";
import {getToken} from "@/api/file";
import dayjs from 'dayjs';
import OSS from "ali-oss";

export default {
  name: "PostEditor",
  props: ['initialData'],
  emits: ['close'],
  data() {
    return {
      stsToken: null,
      uploadQueue: [],
      uploadProgress: {},
      post: {
        title: '',
        content: '',
        publishTime: '',
        visibility: 'PUBLIC_POST',
        media: [], // 合并图片和视频为一个列表
        tags: [],
        communityId: ''
      },
      newTag: '',
      isSubmitting: false,
      mediaIdCounter: 0,
      myCommunity: [
        {
          id: 1,
          name: '社区1',
          avatar: 'https://randomuser.me/api/portraits/men/32.jpg',
        },
        {
          id: 2,
          name: '社区2',
          avatar: 'https://randomuser.me/api/portraits/men/32.jpg',
        },
        {
          id: 3,
          name: '社区3',
          avatar: 'https://randomuser.me/api/portraits/men/32.jpg',
        },
      ],
      visibilityList: [
        {
          value: 'PUBLIC_POST',
          label: '公开帖子'
        },
        {
          value: 'COMMUNITY_NOTICE',
          label: '社区公告'
        },
        {
          value: 'COMMUNITY_PRIVATE_POST',
          label: '社区(私有)'
        },
        {
          value: 'COMMUNITY_PUBLIC_POST',
          label: '社区(公开)'
        },
      ],
      showCommunityDropdown: false,
      selectedCommunity: {
        id: '1',
        name: '社区1',
        avatar: 'https://randomuser.me/api/portraits/men/32.jpg'
      }
    };
  },
  computed: {
    allMedia() {
      const imageExtensions = /\.(jpe?g|png|gif|bmp|webp|svg)$/i;
      const videoExtensions = /\.(mp4|webm|ogg|mov)$/i;

      return this.post.media.map((url, index) => {
        if (typeof url !== 'string') {
          console.warn('Invalid media URL:', url);
          return null;
        }

        let type = 'video';
        if (imageExtensions.test(url)) {
          type = 'image';
        } else if (videoExtensions.test(url)) {
          type = 'video';
        }

        return {
          id: `media-${this.mediaIdCounter++}`,
          type,
          url,
          imageId: `image-${index}`,
          videoId: `video-${index}`
        };
      }).filter(Boolean);
    }
  },
  created() {
    if (this.initialData) {
      this.post = {...this.post, ...this.initialData};
    }
  },
  methods: {
    close() {
      this.$emit('close');
    },
    openFileDialog() {
      if (this.mediaCount >= 12) {
        this.showToast('最多只能上传12个媒体文件', 'warning');
        return;
      }
      this.$refs.fileInput.click();
    },

    async handleFileUpload(event) {
      const files = event.target.files;
      if (!files.length) return;

      try {
        const remainingSlots = 12 - this.post.media.length;
        if (remainingSlots <= 0) {
          this.showToast('最多只能上传12个媒体文件', 'warning');
          return;
        }

        // 获取STS令牌
        if (!this.stsToken) {
          this.stsToken = await getToken();
        }

        // 初始化OSS客户端
        const client = new OSS({
          region: this.stsToken.region,
          bucket: this.stsToken.bucket,
          accessKeyId: this.stsToken.accessKeyId,
          accessKeySecret: this.stsToken.accessKeySecret,
          stsToken: this.stsToken.securityToken,
          refreshSTSToken: async () => {
            const newToken = await getToken();
            return {
              accessKeyId: newToken.accessKeyId,
              accessKeySecret: newToken.accessKeySecret,
              stsToken: newToken.securityToken
            };
          },
          refreshSTSTokenInterval: 300000
        });

        // 并行上传所有文件
        const uploadPromises = [];

        for (let i = 0; i < Math.min(files.length, remainingSlots); i++) {
          const file = files[i];
          uploadPromises.push(
              this.uploadSingleFile(client, file)
          );
        }

        // 等待所有上传完成
        const results = await Promise.all(uploadPromises);

        // 添加到媒体列表
        results.forEach(url => {
          if (url) this.post.media.push(url);
        });

        this.$toast.show(`成功上传 ${results.length} 个文件`, 'success');

      } catch (error) {
        console.error('上传失败:', error);
        this.$toast.show(error.message || '文件上传失败', 'error');
      } finally {
        event.target.value = ''; // 重置文件输入
      }
    },

    // 单个文件上传方法
    async uploadSingleFile(client, file) {
      try {
        const fileName = this.generateFileName(file);
        console.log('开始上传:', file.name, '=>', fileName);

        // 使用简单上传（自动处理分片）
        const result = await client.put(fileName, file, {
          headers: {
            'x-oss-object-acl': 'public-read' // 设置公开读取
          },
          progress: (p) => {
            console.log(`${file.name} 上传进度: ${Math.floor(p * 100)}%`);
          }
        });

        // 直接使用OSS返回的URL（因为设置了public-read）
        return result.url;

      } catch (error) {
        console.error(`${file.name} 上传失败:`, error);
        this.$toast.show(`${file.name} 上传失败: ${error.message}`, 'error');
        return null;
      }
    },

    // 生成安全的文件名
    generateFileName(file) {
      if (!file || !file.name) {
        throw new Error('无效的文件对象');
      }
      // 获取当前日期
      const now = new Date();
      const year = now.getFullYear();
      const month = String(now.getMonth() + 1).padStart(2, '0');
      const day = String(now.getDate()).padStart(2, '0');
      const dateFolder = `${year}/${month}/${day}`;
      const extension = file.name.split('.').pop().toLowerCase();
      // 生成唯一文件名: 时间 + 随机字符串 + 扩展名
      const randomStr = Math.random().toString(36).substring(2, 8) + Math.random().toString(36).substring(2, 8);
      return `${dateFolder}/${randomStr}.${extension}`;
    },

    mediaCount() {
      return this.post.media.length;
    },

    showToast(message, type = 'info') {
      // 检查是否存在toast插件
      if (this.$toast) {
        this.$toast.show(message, type);
      } else {
        // 降级处理：使用console输出
        console.log(`[${type.toUpperCase()}] ${message}`);
        // 可选：使用原生alert作为备选
        if (type === 'error') {
          alert(message);
        }
      }
    },

    removeMedia(index) {
      this.post.media.splice(index, 1);
    },

    addTag() {
      if (this.newTag.trim()) {
        this.post.tags.push(this.newTag.trim());
        this.newTag = '';
      }
    },

    removeTag(index) {
      this.post.tags.splice(index, 1);
    },

    selectCommunity(community) {
      this.post.communityId = community.id;
      this.selectedCommunity = community;
      this.showCommunityDropdown = false;
    },

    // 发布帖子
    submitPost() {
      if (!this.post.content.trim()) {
        this.$toast.show('请输入帖子内容', 'error');
        return;
      }

      this.isSubmitting = true;

      console.log('提交的帖子数据:', this.post);

      const data = {
        title: this.post.title,
        content: this.post.content,
        postTime: this.post.publishTime === '' ? null : dayjs(this.post.publishTime).format('YYYY-MM-DD HH:mm:ss'),
        type: this.post.visibility,
        imageUrl: this.post.media,
        tag: this.post.tags,
        communityId: this.post.communityId
      };

      addPost(data)
          .then((response) => {
            this.$toast.show('帖子发布成功', 'success');
            this.isSubmitting = false;
            this.close();
          })
          .catch((error) => {
            this.$toast.show('服务器繁忙！', 'error');
            this.close();
          });
    },
  },

}
</script>

<style scoped>
::-webkit-scrollbar {
  width: 4px;
}

::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 10px;
}

::-webkit-scrollbar-thumb {
  background: #d1d5db;
  border-radius: 10px;
}

::-webkit-scrollbar-thumb:hover {
  background: #9ca3af;
}

@keyframes fadeIn {
  from {
    opacity: 0;
    transform: scale(0.95);
  }
  to {
    opacity: 1;
    transform: scale(1);
  }
}

.animate-in {
  animation: fadeIn 0.2s ease-out;
}

button:disabled {
  opacity: 0.7;
  cursor: not-allowed;
}

.opacity-50 {
  opacity: 0.5;
}

.cursor-not-allowed {
  cursor: not-allowed;
}

/* 新增图片预览样式优化 */
.aspect-square img {
  transition: transform 0.3s ease;
}

.aspect-square:hover img {
  transform: scale(1.05);
}

/* 图片加载占位符样式 */
.aspect-square .loading-placeholder {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 100%;
  height: 100%;
  background-color: #f1f1f1;
  border-radius: 0.5rem;
}

/* 删除按钮样式调整 */
.aspect-square .delete-button {
  position: absolute;
  top: 0.5rem;
  right: 0.5rem;
  z-index: 10;
  background-color: rgba(255, 255, 255, 0.9);
  border-radius: 50%;
  width: 2rem;
  height: 2rem;
  display: flex;
  align-items: center;
  justify-content: center;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.aspect-square .delete-button:hover {
  background-color: white;
}
</style>